package com.es.servlet;

import com.es.utils.DBUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 描述:
 * es-servlet-
 *
 * @author Derek
 * 创建时间：2022-04-20 11:48
 */
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //super.service(req, resp);
        request.setCharacterEncoding("utf-8");
        //前端响应
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html><head><title>欢迎使用此系统");
        out.println("</title><head><body>");


        //
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //去数据库中比对
        try {
            Connection connection = DBUtils.getConnection();
            String sql = "select username,password from sys_user where username=? and password = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            ResultSet resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                //登录成功
                out.println("<h3>"+username+",欢迎回来！</h3>");
            }else{
                //用户名或密码有误
                out.println("<a href='login.html'>用户名或密码错误，请重试！</a>");
            }

            resultSet.close();
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        out.println("</body></html>");
        out.flush();
    }
}
